package com.joven.gateway.factory;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author joven_wong
 * 2021/6/22 14:51
 * 类名须为“谓词工厂名（本例中：TimeBetween）” + RoutePredicateFactory
 */
//@Component
public class TimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<TimeBetweenVo> {

    public TimeBetweenRoutePredicateFactory() {
        super(TimeBetweenVo.class);
    }

    /**
     * 实现为谓词判断的方法
     */
    @Override
    public Predicate<ServerWebExchange> apply(TimeBetweenVo config) {
        LocalTime start = config.getStart();
        LocalTime end = config.getEnd();
        return serverWebExchange -> {
            LocalTime now = LocalTime.now();
            return now.isAfter(start) && now.isBefore(end);
        };
//        return new Predicate<ServerWebExchange>(){
//            @Override
//            public boolean test(ServerWebExchange serverWebExchange) {
//                LocalTime now = LocalTime.now();
//                // 判断当前时间是否在在配置的时间范围类
//                return now.isAfter(start) && now.isBefore(end);
//            }
//        };
    }

    /**
     * 设置配置类与配置文件的关系
     * @return List<String>
     */
    @Override
    public List<String> shortcutFieldOrder() {
        /*
         * 配置项是：TimeBetween=上午6:00, 下午1:00
         * 那么按照顺序，start对应的是上午6:00；end对应的是下午1:00
         * 时间格式不是随便配置的，而是Spring Cloud Gateway的默认时间格式
         */
        return Arrays.asList("start", "end");
    }
}
//spring:
//  cloud:
//    gateway:
//      discovery:
//        locator:
//        enabled: false # 要禁止gateway通过服务发现组件转发请求到其他的微服务，开启会导致自定义的路由谓词工厂不生效
//      routes:
//      - id: my-timeBetween # id必须要唯一
//        uri: lb://product-center # 任意一个微服务工程
//        predicates:
//          - TimeBetween=上午7:00,下午11:00
